home *** CD-ROM | disk | FTP | other *** search
- TITLE Binary Search Procedure (EX56.ASM)
- PAGE ,132
- DATA SEGMENT PARA 'DATA'
- START_ADDR DW ?
- DATA ENDS
- OUR_CODE SEGMENT PARA 'CODE'
- PUBLIC B_SEARCH
- B_SEARCH PROC FAR
- ASSUME CS:OUR_CODE,DS:DATA
- PUSH DS ;Save caller's DS register
- ;
- ; To start, find out if AX lies beyond the boundaries of the list.
- ;
- CMP AX,ES:[DI+2] ;Search value < or = first el.?
- JA CHK_LAST ; No. Go check last element
- LEA SI,ES:[DI+2] ; Yes. Fetch addr. of first el.
- JE EXIT_1ST ;If value = 1st element, exit
- STC ;If value < 1st element, set CF
- EXIT_1ST: POP DS ;and then exit
- RET
- CHK_LAST: MOV SI,ES:[DI] ;Point to last element
- SHL SI,1
- ADD SI,DI
- CMP AX,ES:[SI] ;Search value > or = last el.?
- JB SEARCH ; No. Go search list
- JE EXIT_LAST ; Yes. Exit if value = last el.
- STC ;If value > last element, set CF
- EXIT_LAST: POP DS ; and then exit
- RET
- ;
- ; Search for value within the list.
- ;
- SEARCH: MOV START_ADDR,DI ;Save starting address in memory
- MOV SI,ES:[DI] ;Fetch index
- EVEN_IDX: TEST SI,1 ;Force index to an even value
- JZ ADD_IDX
- INC SI
- ADD_IDX: ADD DI,SI ;Calculate next search address
- COMPARE: CMP AX,ES:[DI] ;Search value found?
- JE ALL_DONE ; If so, exit
- JA HIGHER ; Otherwise, find correct half
- ;
- ; These instructions are executed if the search value is lower
- ; in the list.
- ;
- CMP SI,2 ;Index = 2?
- JNE IDX_OK
- NO_MATCH: STC ; If so, set CF
- JE ALL_DONE ; and exit
- IDX_OK: SHR SI,1 ; If not, divide index by 2
- TEST SI,1 ;Force index to an even value
- JZ SUB_IDX
- INC SI
- SUB_IDX: SUB DI,SI ;Calculate next address
- JMP SHORT COMPARE ;Go check this element
- ;
- ; These instructions are executed if the search value is higher
- ; in the list.
- ;
- HIGHER: CMP SI,2 ;Index = 2?
- JE NO_MATCH ; If so, go set CF and exit
- SHR SI,1 ; If not, divide index by 2
- JMP SHORT EVEN_IDX ;Go check next element
- ;
- ; Following are exit instructions.
- ;
- ALL_DONE: MOV SI,DI ;Move compare address into SI
- MOV DI,START_ADDR ;Restore starting address
- POP DS
- RET ; and exit
- B_SEARCH ENDP
- OUR_CODE ENDS
- END B_SEARCH
-